<?php

/**
 * 生产一个可指定长度的随机字符串
 * @param int $length zh - max:1000
 * @param string $type {1:0-9 ; a:a-z ; A:A-Z ;zh|cn; default:mixed}
 * @return string
 */
function randStr($length = 16, $type = "mix")
{
    switch ($type) {
        case '1':
        case 'num':
            $pool = '0123456789';
            break;
        case 'a':
        case 'lower':
            $pool = 'abcdefghijklmnopqrstuvwxyz';
            break;
        case 'A':
        case 'upper':
            $pool = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
        case 'zh':
        case 'cn':
            $pool = getChineseChar($length);
            return $pool;
            break;
        case 'mix':
        default:
            $pool = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            break;
    }

    return substr(str_shuffle(str_repeat($pool, $length)), 0, $length);

}


function getChineseChar($num)  // $num为生成汉字的数量
{
    $b = '';
    $num= ($num>1000)?1000:$num;
    for ($i=0; $i<$num; $i++) {
        // 使用chr()函数拼接双字节汉字，前一个chr()为高位字节，后一个为低位字节
        $a = chr(mt_rand(0xB0,0xD0)).chr(mt_rand(0xA1, 0xF0));
        // 转码
        $b .= iconv('GB2312', 'UTF-8', $a);
    }
    return $b;
}
